<html> 
<head>    
<title>Tablet Master</title>    
	<script type="text/javascript" src="https://www.google.com/jsapi?key=ABQIAAAAv2qC-G4Rrqzj4hnAF64rNRT_ImPw2cwuh07oOpiQ25mnD91EFxTRmOwnQa77QZMlW_s1EI1ynTZpzw"> </script>    
	<script type="text/javascript" src="Queue.js"></script>
  
<script language="javascript" type="text/javascript">  
	var ge;       
	google.load("earth", "1"); 
        //var cam = {};
	var camera;	
	var scale;
	var queue = new Queue();
	var slowdown;
	var tailModel;
	var tailpm;
	var playerid;
	var tail;
	var count=0;
	var slow;
	var rendered;
	var master;
	var rings = new Array();
	var ringpms = new Array();
	var ringmodels = new Array();
	var ringlinks = new Array();
	var ringoriens = new Array();
	var playermodels = new Array();
	var playerpms = new Array();
	var playerlinks = new Array();
	var playeroriens = new Array();


	function init() {          
		google.earth.createInstance('map3d', initCB, failureCB);  
		document.documentElement.style.overflow = 'hidden';	 
		document.body.scroll = "no";
		//cam = document.getElementById("cam");
	
	}
		

	function initCB(instance) { 
		master = true;
	    ge = instance;
	    ge.getWindow().setVisibility(true);  
		ge.getLayerRoot().enableLayerById(ge.LAYER_BUILDINGS, true);  
		ge.getOptions().setFlyToSpeed(ge.SPEED_TELEPORT);
		//ge.getOptions().setGroundLevelViewEnabled(false);
		ge.getNavigationControl().setStreetViewEnabled(false);
		//ge.getNavigationControl().setStreetViewEnabled(false);
		//Alf ge.getSun().setVisibility(true);
		slowdown = 0;
		rendered = false;
			
		var syd = ge.getView().copyAsCamera(ge.ALTITUDE_RELATIVE_TO_GROUND);
		syd.setLatitude(-33.85676);
		syd.setLongitude(151.207897);
		syd.setAltitude(15000);
			
		ge.getView().setAbstractView(syd);
			
		var qryArgs = getQueryStringVars();
			
		if (qryArgs["player"]) {
			playerid = qryArgs["player"];
		}
		if (qryArgs["master"]) {
			if(qryArgs["master"] == 'true') { master = true; }
		}
		//camTil.innerHTML = playerid;
		//playeridprint.innerHTML = playerid;
		if(!master) { ge.getOptions().setMouseNavigationEnabled(false); }
		initPlayers();
		//Alf initRingArray();
		//Alf drawRings();
		//Alf initTail(); 
		DuasWS();	
	}
		
function getQueryStringVars() {

    var server_variables = {};
    var query_string = window.location.search.split( "?" )[ 1 ];
    if ( ! query_string ) return false;
    var get = query_string.split( "&" );
	
    for ( var i=0; i < get.length; i++ ) {

        var pair = get[ i ].split( "=" );
        server_variables[ pair[ 0 ] ] = unescape( pair[ 1 ] );
    }

    return server_variables;
}
		
	function initTail() {
		//Initialises a queue to store models used  to generate the "tail" effect
		//These models will be popped off, generated at a new location, then pushed
		//back onto the queue to be rendered one at a time, maintaining a "trail" state
		var i;
		//var tail;
		var link;
			
		tailpm = ge.createPlacemark('');
		//tailpm.setId("tailpm");
		//tail = ge.createLineString('');
			
		for (i=0;i<20;i++){
			/*var tail = ge.createPlacemark('');
			tailModel = ge.createModel('');
			ge.getFeatures().appendChild(tail);
			link = ge.createLink('');
			link.setHref('http://localhost/tail.dae');
			tailModel.setLink(link);
			tailModel.setAltitudeMode(ge.ALTITUDE_RELATIVE_TO_GROUND);	
			tail.setGeometry(tailModel);
			tail.setName(i.toString()); 
			queue.enqueue(tail);*/
			var point = ge.createPoint('');
			point.setLatitude(0);
			point.setLongitude(0);
			point.setAltitude(100);
			queue.enqueue(point);
		}
		
	
	}
		
	function initRingArray() {
		//Initialises the array storing all of the ring locations; these points are hardcoded locations
			
		//var ring = ge.createCamera('');
		
		//Bridge
		rings[0] = ge.createCamera('');
		rings[0].setLatitude(-33.85206116546625);
		rings[0].setLongitude(151.21075014076803);
		rings[0].setAltitude(400);
		rings[0].setHeading(295);
		rings[0].setTilt(0);
		rings[0].setRoll(0);
			
		//Centerpoint Tower
		rings[1] = ge.createCamera('');
		rings[1].setLatitude(-33.87051713231955);
		rings[1].setLongitude(151.2089196340125);
		rings[1].setAltitude(500);
		rings[1].setHeading(20);
		rings[1].setTilt(0);
		rings[1].setRoll(0);
			
		//Opera House
		rings[2] = ge.createCamera('');
		rings[2].setLatitude(-33.85647746674686);
		rings[2].setLongitude(151.21539736966128);
		rings[2].setAltitude(350);
		rings[2].setHeading(345);
		rings[2].setTilt(0);
		rings[2].setRoll(0);
			
			//Island
			rings[3] = ge.createCamera('');
			rings[3].setLatitude(-33.85277242888568);
			rings[3].setLongitude(151.19518041484696);
			rings[3].setAltitude(500);
			rings[3].setHeading(100);
			rings[3].setTilt(0);
			rings[3].setRoll(0);
			 
			//Island 2
			rings[4] = ge.createCamera('');
			rings[4].setLatitude(-33.847886442832646);
			rings[4].setLongitude(151.17302947077044);
			rings[4].setAltitude(450);
			rings[4].setHeading(-80);
			rings[4].setTilt(0);
			rings[4].setRoll(0);
			
			//Intersection
			rings[5] = ge.createCamera('');
			rings[5].setLatitude(-33.83899738245863);
			rings[5].setLongitude(151.14492521934753);
			rings[5].setAltitude(425);
			rings[5].setHeading(-100);
			rings[5].setTilt(0);
			rings[5].setRoll(0);
			
			//Sticky Outy Bit
			rings[6] = ge.createCamera('');
			rings[6].setLatitude(-33.85295290380713);
			rings[6].setLongitude(151.11663584044823);
			rings[6].setAltitude(475);
			rings[6].setHeading(5);
			rings[6].setTilt(0);
			rings[6].setRoll(0);
			
			//Park
			rings[7] = ge.createCamera('');
			rings[7].setLatitude(-33.87265406702083);
			rings[7].setLongitude(151.11497495616567);
			rings[7].setAltitude(450);
			rings[7].setHeading(155);
			rings[7].setTilt(0);
			rings[7].setRoll(0);
			
			//Park
			rings[8] = ge.createCamera('');
			rings[8].setLatitude(-33.88634599261195);
			rings[8].setLongitude(151.13468354866743);
			rings[8].setAltitude(475);
			rings[8].setHeading(100);
			rings[8].setTilt(0);
			rings[8].setRoll(0);
			
			//Road
			rings[9] = ge.createCamera('');
			rings[9].setLatitude(-33.887918557061845);
			rings[9].setLongitude(151.16950205667513);
			rings[9].setAltitude(490);
			rings[9].setHeading(85);
			rings[9].setTilt(0);
			rings[9].setRoll(0);
			
			//Finish
			rings[10] = ge.createCamera('');
			rings[10].setLatitude(-33.8844656522078);
			rings[10].setLongitude(151.20894468812577);
			rings[10].setAltitude(490);
			rings[10].setHeading(85);
			rings[10].setTilt(0);
			rings[10].setRoll(0);
			
						//Finish
		rings[11] = ge.createCamera('');
		rings[11].setLatitude(-33.85543128617356);
		rings[11].setLongitude(151.21241027523143);
		rings[11].setAltitude(7999.903289511771);
		rings[11].setHeading(85);
		rings[11].setTilt(0);
		rings[11].setRoll(0);
	}
	
	function drawRings() {
		//Draw all of the rings in the array			
				
		var i;
				
		for(i = 0; i <= 10; i++) {
			ringmodels[i] = ge.createModel('');
			ringlinks[i] = ge.createLink('');
			if(i == 1) {
					
				ringlinks[i].setHref('http://192.168.0.233/bluering.dae');
			} else if(i == 10) {
				ringlinks[i].setHref('http://192.168.0.233/greenring.dae');
			} else if(i == 11){ 
				ringlinks[i].setHref('http://192.168.0.233/Imperial.dae');
			} else {
				ringlinks[i].setHref('http://192.168.0.233/redring.dae');
			} 
			ringoriens[i] = ge.createOrientation('');
			ringpms[i] = ge.createPlacemark('');
			ringpms[i].setName('ring' + i);
			ge.getFeatures().appendChild(ringpms[i]);
			ringoriens[i].setHeading(rings[i].getHeading());
			ringoriens[i].setTilt(rings[i].getTilt());
			ringoriens[i].setRoll(rings[i].getRoll());
			var ringscale = ge.createScale('');
			if (i == 11){
				ringscale.set(100, 100, 100);}
			else{
				ringscale.set(10, 10, 10);}
			ringmodels[i].setScale(ringscale);
			ringmodels[i].setOrientation(ringoriens[i]);
			ringmodels[i].setLink(ringlinks[i]);
			ringmodels[i].setAltitudeMode(ge.ALTITUDE_RELATIVE_TO_GROUND);	
			ringmodels[i].getLocation().setLatLngAlt(rings[i].getLatitude(),rings[i].getLongitude(),rings[i].getAltitude());				
			ringpms[i].setGeometry(ringmodels[i]);
		}
	}
		
	function initPlayers() {
		//Initialises all of the player data
		var i;
		for(i = 0; i < 3; i++) {
			playermodels[i] = ge.createModel('');
			playerlinks[i] = ge.createLink('');
			playeroriens[i] = ge.createOrientation('');
			if(i == 0) {
				playerlinks[i].setHref('http://192.168.0.233/xwing1.dae');
			} else {
					playerlinks[i].setHref('http://192.168.0.233/tie.dae');
			}
			playerpms[i] = ge.createPlacemark('');
			playerpms[i].setName('player' + i);
			ge.getFeatures().appendChild(playerpms[i]);
			playermodels[i].setLink(playerlinks[i]);
			playermodels[i].setAltitudeMode(ge.ALTITUDE_RELATIVE_TO_GROUND);				
			playerpms[i].setGeometry(playermodels[i]);
		}
	}

	function failureCB(errorCode) {      
	} 


	google.setOnLoadCallback(init); 
	
	var wsUri = "ws://192.168.0.233:3000/relay"; 
	var output;  
	
	function DuasWS() { 
		output = document.getElementById("output");
		websocket = new WebSocket(wsUri); 
		if(master) { google.earth.addEventListener(ge, 'frameend', serialize); }
		websocket.onopen = function(evt) { onOpen(evt) }; 
		websocket.onclose = function(evt) { onClose(evt) }; 
		websocket.onmessage = function(evt) { onMessage(evt) }; 
		websocket.onerror = function(evt) { onError(evt) }; 
			
	}  
		 
	
	function onOpen(evt) {
		//writeToScreen("Open");
	}  
		
	function onClose(evt) { 
		//writeToScreen("Closed");
	}  
	
	function onMessage(evt) {
		//writeToScreen("Message");
		//writeToScreen(evt.data);
		deSerialize(evt.data);
	}  
	
	function onError(evt) {
		//writeToScreen("Error");
	}  
	
	function doSend(message) { 
		//writeToScreen("Sent");
		//writeToScreen(message);
		//console.log("send:"+message);
		websocket.send(message); 
	}  
		
	function writeToScreen(message) { 
		var pre = document.createElement("p"); 
		pre.style.wordWrap = "break-word"; 
		pre.innerHTML = message; 
		output.appendChild(pre); 
	}  

function serialize() {
		
	var camS = {};
	
	count++;
	//if (i==2) {
	var cameraS = ge.getView().copyAsCamera(ge.ALTITUDE_RELATIVE_TO_GROUND);

	camS.cou = count;
	camS.id = 2; // was playerid set TABLET always to player 2.
	camS.Lat = cameraS.getLatitude();
	camS.Lon = cameraS.getLongitude();
	camS.Til = cameraS.getTilt();
	camS.Rol = cameraS.getRoll();
	camS.Alt = cameraS.getAltitude();
	camS.Hea = cameraS.getHeading(); 
			
	var JSONcam = JSON.stringify(camS);
		
	doSend(JSONcam);
		
	// printCamera();
	//	i=0;
	//	}

}		
		
function deSerialize(message) {
	var cam = JSON.parse(message);  
	if(cam.id != playerid) {
			
		//var current = ge.getView().copyAsCamera(ge.ALTITUDE_RELATIVE_TO_GROUND);
		//var scale = (current.getAltitude() - cam.Alt) / 100;
		//if(scale < 0) { scale = -scale; }
		var scale = (cam.Alt / 1000) * (cam.Alt / 1000);
		if (scale < 3) { scale = 3; }
		if (scale > 100) { scale = 100; }

		if (cam.id == 1) { // flip XWing (Alf)
			playeroriens[cam.id - 1].setHeading(cam.Hea + 180);
			playeroriens[cam.id - 1].setRoll(cam.Rol + 180);	
			playeroriens[cam.id - 1].setTilt(cam.Til + 90);
		} else { // TIE
			playeroriens[cam.id - 1].setHeading(cam.Hea);
			playeroriens[cam.id - 1].setRoll(cam.Rol + 180);	
			playeroriens[cam.id - 1].setTilt(270 - cam.Til);
		}
		//playeroriens[cam.id - 1].setRoll(cam.Rol + 180);	
		//playeroriens[cam.id - 1].setTilt(cam.Til+90);
	
		playermodels[cam.id - 1].setOrientation(playeroriens[cam.id - 1]);
		playermodels[cam.id - 1].setAltitudeMode(ge.ALTITUDE_RELATIVE_TO_GROUND);
		playermodels[cam.id - 1].getLocation().setLatLngAlt(cam.Lat,cam.Lon,cam.Alt);
		var modscale = ge.createScale('');
		modscale.set(scale, scale, scale);
		playermodels[cam.id - 1].setScale(modscale); 
		playerpms[cam.id - 1].setGeometry(playermodels[cam.id - 1]);
	
		//draw(placemark, model, 500);
		var tailpm = ge.createPlacemark('');

		slowdown = slowdown + 1;
		if (slowdown > 30) {
			updateTail(cam.Lat, cam.Lon, cam.Alt);
			drawTail();
			slowdown = 0;
			/*
			//Remove the last tail object
			//ge.getFeatures().removeChild(ge.getFeatures().getFirstChild());	
			var tail = queue.dequeue();
			//writeToScreen(tail.getName());
			queue.enqueue(draw(tail, tailModel, 500));
			var i;
			for(i = 0; i < 20; i++) {
				var cont = ge.createPlacemark('');
				ge.getFeatures().appendChild(cont);
				var print = queue.dequeue();
				writeToScreen(print.getName());
				print.setGeometry();
				enqueue(print);
			}
			*/
		}
	//printCamera();	
	}
}
	
function updateTail(lat, lon, alt) {
	var point = ge.createPoint('');
	point = queue.dequeue();
	point.setLatitude(lat);
	point.setLongitude(lon);
	point.setAltitude(alt);
	queue.enqueue(point);
}

function drawTail() {
	
	var tail = ge.createLineString('');
	tailpm.setGeometry(tail);
	
	tail.setAltitudeMode(ge.ALTITUDE_RELATIVE_TO_GROUND);
	tail.setExtrude(false);
	tail.setTessellate(false);
	
	
	var	i;
	var point;
	for(i = 0; i < 20; i++) {
		point = queue.dequeue();
		tail.getCoordinates().pushLatLngAlt(point.getLatitude(), point.getLongitude(), point.getAltitude());
		queue.enqueue(point);
	}
	tailpm.setStyleSelector(ge.createStyle(''));
	var tailStyle = tailpm.getStyleSelector().getLineStyle();
	tailStyle.setWidth(10);
	if(playerid == 1) {
		tailStyle.getColor().set('FF0000FF');
	} else {
		tailStyle.getColor().set('FFFF0000');
	}
	ge.getFeatures().appendChild(tailpm);
}
	
function printCamera() {
	var current = ge.getView().copyAsCamera(ge.ALTITUDE_RELATIVE_TO_GROUND);
	camLat.innerHTML = current.getLatitude();
	camLon.innerHTML = current.getLongitude();
	camTil.innerHTML = current.getTilt();
	camRol.innerHTML = current.getRoll();
	camAlt.innerHTML = current.getAltitude();
	camHea.innerHTML = current.getHeading()
}
	
function features(){
	var feat = ge.getFeatures().getChildNodes();
	var length = feat.getLength();
	var k=0;
	while(k!=length){
		writeToScreen(k + " " + feat.item(k).getType() + " " + feat.item(k).getName() + " " + feat.item(k).getVisibility());

		k++;
	}
	writeToScreen(ge.getNavigationControl().getStreetViewEnabled());	
}

function remove(){
	ge.getFeatures().removeChild(ge.getFeatures().getFirstChild());
}

function time(){
	writeToScreen(ge.getTimePrimitive());	
}
function sun(flag) {
	if (flag == "1") { 
		doSend("cmd sun on");
		ge.getSun().setVisibility(true);
	} else {
		doSend("cmd sun off");
		ge.getSun().setVisibility(false);
	}
}

function gridlines(flag) {
	if (flag == "1") {
		doSend("cmd grid on");
		ge.getOptions().setGridVisibility(true);
	} else {
		doSend("cmd grid off");
		ge.getOptions().setGridVisibility(false);
	}
}

function send_refresh() {
	doSend("cmd refresh");
	location.reload(true); // force browser reget of current page
}

function layer(layer, flag) {
	if (flag == 1) {
		doSend("cmd layer " + layer + " on");
		flag = true;
	} else {
		doSend("cmd layer " + layer + " off");
		flag = false;
	}
	
	if (layer == "ROADS")  {
		ge.getLayerRoot().enableLayerById(ge.LAYER_ROADS, flag);
	} else if (layer == "TREES") {
		ge.getLayerRoot().enableLayerById(ge.LAYER_TREES, flag);
	} else if (layer == "BORDERS") {
		ge.getLayerRoot().enableLayerById(ge.LAYER_BORDERS, flag);
	} else if (layer == "BUILDINGS") {
		ge.getLayerRoot().enableLayerById(ge.LAYER_BUILDINGS, flag);
	}
}

function modes( mode ) {
	if (mode == 1) {
		doSend("cmd surf");
	} else if (mode == 2) {
		doSend("cmd follow");
	}
}

function conference( demo ) {
	if( demo == 1) {
		doSend("cmd util1");
	} else if ( demo == 2 ) {
		doSend("cmd resource1");
	} else if ( demo == 3 ) {
		doSend("cmd util2");
	} else if ( demo == 4 ) {
		doSend("cmd gov1");
	} else if ( demo == 5 ) {
		doSend("cmd gov2");
	} else if ( demo == 6 ) {
		doSend("cmd telco2");
	}
}
	window.addEventListener("load", init, false);  

</script> 	
<style ttype="text/css">
.btn { width:140; height:70; }
</style>
</head> 
<body scroll="no" topmargin="0px" leftmargin="0px">
<table border="0">
<tr>
<td width="25%"></br>
<button type="button" onclick=modes(1) class="btn" >CONTROL BALL</button>
<button type="button" onclick=modes(2) class="btn">CONTROL RIG</button></br></br>
<button type="button" onclick=layer("BUILDINGS",1) class="btn" style="">BUILDINGS ON</button>
<button type="button" onclick=layer("BUILDINGS",0) class="btn" style="">BUILDINGS OFF</button>
<button type="button" onclick=layer("BORDERS",1) class="btn">LABELS ON</button>
<button type="button" onclick=layer("BORDERS",0) class="btn">LABELS OFF</button>
<button type="button" onclick=layer("ROADS",1) class="btn">ROADS ON</button>
<button type="button" onclick=layer("ROADS",0) class="btn">ROADS OFF</button>
<button type="button" onclick=conference(5) class="btn">Gov 2</button>
<button type="button" onclick=conference(6) class="btn">Telco 2</button>
</br></br>
<button type="button" onclick=conference(1) class="btn" style="">Util 1</button>
<button type="button" onclick=conference(2) class="btn" style="">Resource 1</button>
<button type="button" onclick=conference(3) class="btn" >Util 2</button>
<button type="button" onclick=conference(4) class="btn">Gov 1</button></br></br>
<button type="button" onclick=send_refresh() style="width:284; height:70;">RELOAD RIG BROWSERS</button>
</td>
<td align="center" valign="center">
<img src="/images/wonderama-surfer.png" width="500"></br></br>
<div id="map3d" style="width:640px; height:400px;"></div>
</td>
</tr>
</table>
<!--
<div id="debug">
 	<button type="button" onclick=printCamera()>Show Camera</button>
	</br><p style="font-family:monospace">
	Player ID = <label id="playeridprint"></label>
	Cam.Lat = <label id="camLat"></label> Cam.Long = <label id="camLon"></label> Cam.Alt = <label id="camAlt"></label></br>
	Cam.Tilt = <label id="camTil"></label> Cam.Roll = <label id="camRol"></label>Cam.Head = <label id="camHea"></label>
	</p>
<div id="output"></div>
</div>
-->
</body> 
</html>